package com.hspedu.udp;

import java.io.IOException;
import java.net.*;

/**
 * @author 谷其昊
 * @version 1.0
 * @date 2022/3/2
 * @time 23:23
 */
public class UDPSenderB {
    public static void main(String[] args) throws IOException {
        //1. 创建一个datagramsocket对象
        DatagramSocket datagramSocket = new DatagramSocket(9998);

        //2. 创建数据数组并装包
        byte[] bytes = "hello,明天吃火锅~".getBytes();
        DatagramPacket datagramPacket = new DatagramPacket(bytes, bytes.length, InetAddress.getLocalHost(), 9999);

        datagramSocket.send(datagramPacket);

        //接收A发来的消息
        byte[] buf = new byte[1024];
        DatagramPacket packet = new DatagramPacket(buf, buf.length);
        datagramSocket.receive(packet);

        //拆包
        String s = new String(packet.getData(), packet.getOffset(), packet.getLength());
        System.out.println(s);

    }
}
